// 获取并渲染
function renderCategory() {
    $.ajax({
        // type: 'get',
        url: '/my/category/list',
        success: function (res) {
            console.log(res);
            if (res.status == 0) {
                let arr = []
                res.data.forEach(item => {
                    arr.push(`<tr>
                    <td>${item.name}</td>
                    <td>${item.alias}</td>
                    <td>
                        <button data-id=${item.id} data-name=${item.name} data-alias=${item.alias} type="button" class="layui-btn layui-btn-xs layui-btn-normal" >修改</button>
                        <button type="button" class="layui-btn layui-btn-xs layui-btn-danger" id="${item.id}">删除</button>
                    </td>
                </tr>`)
                })
                $('tbody').html(arr.join(""))
            }
        }
    })
}
renderCategory()

// 添加弹出层
let p
$('#btnn').on('click', function () {
    //页面层
    p = layer.open({
        type: 1,
        skin: 'layui-layer-rim', //加上边框
        area: ['420px', '240px'], //宽高
        content: $('#tpl-add').html()
    });
})

// 表单提交
$('body').on('submit', '#add-form', function (e) {
    e.preventDefault();
    let data = $('#add-form').serialize()
    $.ajax({
        url: '/my/category/add',
        type: 'post',
        data: data,
        success: function (res) {
            console.log(res);
            layer.msg(res.message)
            if (res.status == 0) {
                renderCategory()
                layer.close(p)
            }
        }
    })
})


// 删除
$('body').on('click', '.layui-btn-danger', function () {
    let id = $(this).attr('id')
    console.log(id);
    $.ajax({
        url: '/my/category/delete',
        data: { id: id },
        success: function (res) {
            console.log(res);
            layer.msg(res.message)
            if (res.status == 0) {
                renderCategory()
            }
        }
    })
})

// 修改
let o
let form = layui.form
$('tbody').on('click', '.layui-btn-normal', function () {
    let data = $(this).data()
    console.log(data);
    //页面层
    o = layer.open({
        type: 1,
        skin: 'layui-layer-rim', //加上边框
        area: ['420px', '240px'], //宽高
        content: $('#tpl-xiugai').html(),
        success: function () {
            // 数据回填
            form.val('huit', data)
        }
    });
})

$('body').on('submit', '#xiugai-form', function (e) {
    e.preventDefault()
    let data = $(this).serialize()
    $.ajax({
        url: '/my/category/update',
        type: 'post',
        data: data,
        success: function (res) {
            console.log(res);
            layer.msg(res.message)
            if (res.status == 0) {
                renderCategory()
                layer.close(o)

            }

        }
    })

})

